package com.das.mechanic_base.widget;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.das.mechanic_base.R;
import com.das.mechanic_base.adapter.groundpush.X3SelectGiftSubmitAdapter;
import com.das.mechanic_base.app.X3AppRouterConstants;
import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.base.X3BaseBottomSheetDialog;
import com.das.mechanic_base.bean.alone.SpeechBean;
import com.das.mechanic_base.bean.main.GiftBalanceBean;
import com.das.mechanic_base.bean.main.GiftBalanceSubmitBean;
import com.das.mechanic_base.bean.main.GiftBalanceSuccessBean;
import com.das.mechanic_base.mapi.api.NetWorkHttp;
import com.das.mechanic_base.mapi.response.HttpCallBack;
import com.das.mechanic_base.mapi.schedulers.RxSchedulersHelper;
import com.das.mechanic_base.app.X3RouterCenter;
import com.das.mechanic_base.utils.X3BaseDialogUtil;
import com.das.mechanic_base.utils.LanguageUtiles;
import com.das.mechanic_base.utils.SpHelper;
import com.das.mechanic_base.utils.X3ToastUtils;
import com.google.gson.Gson;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.umeng.analytics.MobclickAgent;

import java.util.List;

import static android.text.InputType.TYPE_TEXT_FLAG_MULTI_LINE;

/**
 * 赠送余额-下一步
 */
public class X3BottomGiftBalanceTWDialog extends X3BaseBottomSheetDialog implements View.OnClickListener {
    private TextView tv_cancel;
    private TextView gift_two_title_tv;
    private Button gift_btn_sure;//确认按钮
    private EditText et_input;//语音输入框BottomGiftBalanceTWDialog
    private TextView tv_sound;//点击语音按钮
    private X3AloneSoundView as_view;
    private TextView tv_end;
    private LinearLayout ll_start;
    private NestedScrollView gift_nested_scroll_view;
    private Button gift_btn_sure_submit;//提交按钮
    private RecyclerView gift_money_recycler_view;
    private RelativeLayout include_one_rl;
    private RelativeLayout include_two_rl;
    private SpeechRecognizer mIat;
    private X3SelectGiftSubmitAdapter selectGiftSubmitAdapter;
    private int isSelectMoney;
    private int carOwnerNameUserId;//赠送余额的时候，将这个id一直传下去，提交的时候需要用到
    private String carOwnerName;//车主名称
    private String verificationType;//判断余额是否是所有门店还是单独门店的

    public X3BottomGiftBalanceTWDialog(@NonNull Context context) {
        super(context);
    }

    @Override
    protected boolean getDialogCancel() {
        return false;
    }

    @Override
    protected void initView() {
        include_two_rl = getView(R.id.include_two_rl);
        include_one_rl = getView(R.id.include_one_rl);
        gift_two_title_tv = getView(R.id.gift_two_title_tv);
        gift_nested_scroll_view = getView(R.id.gift_nested_scroll_view);
        gift_btn_sure_submit = getView(R.id.gift_btn_sure_submit);
        ll_start = getView(R.id.ll_start);
        tv_end = getView(R.id.tv_end);
        as_view = getView(R.id.as_view);
        tv_sound = getView(R.id.tv_sound);
        et_input = getView(R.id.et_input);
        tv_cancel = getView(R.id.tv_cancel);
        gift_btn_sure = getView(R.id.gift_btn_sure);
        gift_money_recycler_view = getView(R.id.gift_money_recycler_view);
        //初始化点击事件
        tv_cancel.setOnClickListener(this);
        gift_btn_sure.setOnClickListener(this);
        tv_sound.setOnClickListener(this);
        gift_btn_sure_submit.setOnClickListener(this);
        initEvent();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.x3_gift_balance_two_bottom_dialog;
    }

    /**
     * 上一级传过来的数据
     *
     * @param giftBalanceBeans
     * @param isSelectMoneys     //选中的额度
     * @param carOwnerNameUserId 车主ID
     */
    public void setDate(GiftBalanceBean giftBalanceBeans, int isSelectMoneys, int carOwnerNameUserId) {
        this.isSelectMoney = isSelectMoneys;
        this.carOwnerNameUserId = carOwnerNameUserId;
        this.carOwnerName = giftBalanceBeans.getCarOwnerName();
        this.verificationType=giftBalanceBeans.getVerificationType();
        String moneyUnit = (String) SpHelper.getData(X3Constent.MONEYCODE, "£");
        String money = String.format(mContext.getString(R.string.x3_gift_money_custom_right_tv), isSelectMoney+"",moneyUnit);
        gift_two_title_tv.setText(String.format(mContext.getString(R.string.x3_gift_money_tips),money));
        List<GiftBalanceBean.CreditPresentVoListBean> mList = giftBalanceBeans.getCreditPresentVoList();
        GiftBalanceBean.CreditPresentVoListBean creditPresentVoListBean = new GiftBalanceBean.CreditPresentVoListBean();
        //这里获取当前技师的名称，进入在本店历史上对该客户的余额赠送记录的基础上，增加一条当前赠送的记录（此记录非实际赠送的记录，仅起到提示作用，当取消赠送后，不再显示再此
        String userName = (String) SpHelper.getData("name", "");
        creditPresentVoListBean.setOperatorName(userName);
        creditPresentVoListBean.setPeriodDesc(mContext.getString(R.string.x3_today_ye));
        creditPresentVoListBean.setPresentMoney(isSelectMoneys);
        mList.add(0, creditPresentVoListBean);
        //设置第一条数据为插入的本地数据
        selectGiftSubmitAdapter.changeData(giftBalanceBeans.getCreditPresentVoList(), isSelectMoneys);
    }

    protected void initEvent() {
        et_input.setHint(mContext.getString(R.string.x3_please_input_gift_please));
        et_input.setInputType(TYPE_TEXT_FLAG_MULTI_LINE);
        et_input.setSingleLine(false);
        et_input.addTextChangedListener(phonrWatcher);
        gift_money_recycler_view.setLayoutManager(new LinearLayoutManager(mContext));
        selectGiftSubmitAdapter = new X3SelectGiftSubmitAdapter(mContext);
        gift_money_recycler_view.setAdapter(selectGiftSubmitAdapter);
    }

    TextWatcher phonrWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.toString().length() > 0) {
                changeBtnStatus(true);
            } else {
                changeBtnStatus(false);
            }
        }
    };

    /**
     * 改变按钮是否可点击
     *
     * @param isClick
     */
    private void changeBtnStatus(boolean isClick) {
        gift_btn_sure_submit.setBackgroundColor(isClick ? Color.parseColor("#0077ff") : Color.parseColor("#D5D5D5"));
       // gift_btn_sure_submit.setEnabled(isClick);
    }

    /**
     * 两种布局切换
     *
     * @param isClick
     */
    private void changeSubmitStatus(boolean isClick) {
        //布局二确认显示
        gift_btn_sure.setVisibility(isClick ? View.VISIBLE : View.GONE);
        include_two_rl.setVisibility(isClick ? View.VISIBLE : View.GONE);
        //布局一提交显示
        gift_btn_sure_submit.setVisibility(isClick ? View.GONE : View.VISIBLE);
        include_one_rl.setVisibility(isClick ? View.GONE : View.VISIBLE);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.tv_cancel) {
            X3BaseDialogUtil baseDialogUtil = X3BaseDialogUtil.showDialog((Activity) mContext, R.layout.x3_gift_success_dialog);
            baseDialogUtil.setText(R.id.tv_noice, String.format(mContext.getString(R.string.x3_gift_money_dalog_left_tv), carOwnerName));
            baseDialogUtil.getView(R.id.btn_sure).setOnClickListener(v -> {
                dismiss();
                baseDialogUtil.cancel();
            });
            baseDialogUtil.getView(R.id.btn_cancel).setOnClickListener(v -> {
                baseDialogUtil.cancel();
            });
        } else if (id == R.id.gift_btn_sure_submit) {// 点击提交
            if (TextUtils.isEmpty(et_input.getText().toString())) {
                et_input.requestFocus();
                et_input.setFocusable(true);
                et_input.setFocusableInTouchMode(true);
                InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(et_input, 0);
                X3ToastUtils.showMessage(mContext.getString(R.string.x3_please_input_gift_please));
                return;
            }
            changeSubmitStatus(true);
        } else if (id == R.id.gift_btn_sure) {// 点击确认
            submitData();
        } else if (id == R.id.tv_sound) {// 点击语音之后
            XXPermissions.with(mContext)
                    .permission(Permission.RECORD_AUDIO)
                    .request(new OnPermissionCallback() {
                        @Override
                        public void onGranted(List<String> permissions, boolean all) {
                            if (all) {
                                startSoundEdit();
                                tv_sound.setVisibility(View.GONE);
                                ll_start.setVisibility(View.VISIBLE);
                                as_view.startAnim();
                                new Handler().post(() -> gift_nested_scroll_view.fullScroll(ScrollView.FOCUS_DOWN));
                            } else {
                                XXPermissions.startPermissionActivity(mContext, permissions);
                            }
                        }

                        @Override
                        public void onDenied(List<String> permissions, boolean never) {
                            XXPermissions.startPermissionActivity(mContext, permissions);
                        }
                    });
        }
    }


    private void submitData() {
        GiftBalanceSubmitBean giftBalanceSubmitBean = new GiftBalanceSubmitBean();
        giftBalanceSubmitBean.setPresentMoney(isSelectMoney);//传赠送钱数
        giftBalanceSubmitBean.setCarOwnerUserId(carOwnerNameUserId);//传赠送的车主ID
        giftBalanceSubmitBean.setPresentReason(et_input.getText().toString());//原因
        NetWorkHttp.getApi().saveCreditPresent(giftBalanceSubmitBean)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<GiftBalanceSuccessBean>() {
                    @Override
                    protected void onDone(GiftBalanceSuccessBean giftBalanceSuccessBean) {
                        dismiss();
                        String brandAndStoreBaseName =giftBalanceSuccessBean.getBrandAndStoreBaseName();

                        Bundle bundle = new Bundle();
                        bundle.putString("brandAndStoreBaseName",brandAndStoreBaseName);
                        bundle.putString("verificationType",verificationType);
                        X3RouterCenter.startNavigate(X3AppRouterConstants.Router.GIFT_SUCCESS,bundle);

//                        Intent intent = new Intent(mContext, GiftDonationSuccessActivity.class);
//                        intent.putExtra("brandAndStoreBaseName",brandAndStoreBaseName);
//                        intent.putExtra("verificationType",verificationType);
//                        mContext.startActivity(intent);
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {
                    }
                });
    }


    /**
     * 语音听写
     */
    private void startSoundEdit() {

        mIat = SpeechRecognizer.createRecognizer(mContext, i -> Log.e("SSSS", "初始化：" + i));

        //设置语法ID和 SUBJECT 为空，以免因之前有语法调用而设置了此参数；或直接清空所有参数，具体可参考 DEMO 的示例。
        mIat.setParameter(SpeechConstant.CLOUD_GRAMMAR, null);
        mIat.setParameter(SpeechConstant.SUBJECT, null);
        //设置返回结果格式，目前支持json,xml以及plain 三种格式，其中plain为纯听写文本内容
        mIat.setParameter(SpeechConstant.RESULT_TYPE, "json");

        //此处engineType为“cloud”
        mIat.setParameter(SpeechConstant.ENGINE_TYPE, "cloud");
        //设置语音输入语言，zh_cn为简体中文
        if (LanguageUtiles.isZhRCN()) {
            mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        }else {
            mIat.setParameter(SpeechConstant.LANGUAGE, "en_us");
        }
        //设置结果返回语言
        mIat.setParameter(SpeechConstant.ACCENT, "mandarin");
        // 设置语音前端点:静音超时时间，单位ms，即用户多长时间不说话则当做超时处理
        //取值范围{1000～10000}
        mIat.setParameter(SpeechConstant.VAD_BOS, "10000");
        //设置语音后端点:后端点静音检测时间，单位ms，即用户停止说话多长时间内即认为不再输入，
        //自动停止录音，范围{0~10000}
        mIat.setParameter(SpeechConstant.VAD_EOS, "10000");
        //设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
        mIat.setParameter(SpeechConstant.ASR_PTT, "1");

        mIat.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");

        //开始识别，并设置监听器
        mIat.startListening(new RecognizerListener() {
            @Override
            public void onVolumeChanged(int i, byte[] bytes) {

            }

            @Override
            public void onBeginOfSpeech() {
            }

            @Override
            public void onEndOfSpeech() {
                ll_start.setVisibility(View.GONE);
                tv_sound.setVisibility(View.VISIBLE);
                as_view.stopAnim();

            }

            @Override
            public void onResult(RecognizerResult recognizerResult, boolean b) {
                SpeechBean speechBean = new Gson().fromJson(recognizerResult.getResultString(), SpeechBean.class);
                List<SpeechBean.WsBean> ws = speechBean.getWs();
                String strContent = "";
                for (SpeechBean.WsBean wsBean : ws) {
                    strContent = strContent + wsBean.getCw().get(0).getW();
                }
                et_input.setText(et_input.getText().toString() + strContent);
            }

            @Override
            public void onError(SpeechError speechError) {
            }

            @Override
            public void onEvent(int i, int i1, int i2, Bundle bundle) {

            }
        });

        tv_end.setOnClickListener(view -> {
            tv_sound.setVisibility(View.VISIBLE);
            ll_start.setVisibility(View.GONE);
            if (mIat == null) {
                X3ToastUtils.showMessage(mContext.getString(R.string.x3_speech_init_error) + "！");
                return;
            }
            mIat.stopListening();
        });

    }

    @Override
    protected void onStart() {
        super.onStart();
        MobclickAgent.onPageStart("赠送余额确认弹窗");
    }

    @Override
    protected void onStop() {
        super.onStop();
        MobclickAgent.onPageEnd("赠送余额确认弹窗");
    }
}
